extends Node

#最大攻击范围
const MAX_RANGE = 150

#此处导入一个场景（PackedScene）
#@export var sword_ability: PackedScene
# 使用load 加载资源
var sword_ability: PackedScene = load("res://scenes/ability/swrod_ability/sword_ability.tscn")

# 获取计时器信号
func _ready() -> void:
	$Timer.timeout.connect(on_timer_timeout)




func on_timer_timeout():

	var player=get_tree().get_first_node_in_group("player")as Node2D
	if player ==null :
		return
	#过滤掉不在最大攻击范围内的敌人
	var enemies =get_tree().get_nodes_in_group("enemy")	
	enemies=enemies.filter(
		func(enemy:Node2D):
			return enemy.global_position.distance_squared_to(player.global_position)<pow(MAX_RANGE,2)
	)
	if enemies.size() == 0:
		return
	
	#获取最近的敌人
	enemies.sort_custom(func(a:Node2D,b:Node2D):
		var a_distance=a.global_position.distance_squared_to(player.global_position)
		var b_distance=b.global_position.distance_squared_to(player.global_position)
		return a_distance<b_distance	
	)
	
	
	var sword_instance=sword_ability.instantiate() as Node2D	
	player.get_parent().add_child(sword_instance)
	sword_instance.global_position=enemies[0].global_position
	sword_instance.global_position+=Vector2.RIGHT.rotated(randf_range(0,TAU))*4
	
	
	var enemty_direction=enemies[0].global_position-sword_instance.global_position
	sword_instance.rotation=enemty_direction.angle()
